package com.ias.agdis_r.activity.message;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ias.agdis_r.activity.BaseKeyListActivity;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.MessageListAdapter;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.db.message.MyMessageBean;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.netservice.ReceiveMessageThread;
import com.ias.agdis_r.util.S;

/**
 * Created by qibo.yu on 2015/9/9.
 */
public class MessageTaskReceived extends BaseKeyListActivity {

    public static final String EXTRA_FKE = "com.ias.agdis_r.activity.message.fke";

    private static final String COLS = "stm,sem,mtn,fln,txt,ack,mti,_id,tgn,fst,readed";
    private static final String ORDER = "ORDER BY stm DESC";

    private MyBeanTempDBHelper<MyMessageBean> messageDBHelper;
    private SQLiteDatabase database;
    private Cursor cursor;

    private MessageListAdapter messageListAdapter;

    private String fke;

    private TextView title;

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            loadData();
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_message_task_received);
        initactionBar();
        setTitle(R.string.MessageTaskReceived);


        fke = getIntent().getStringExtra(EXTRA_FKE);

        messageDBHelper = new MyBeanTempDBHelper<MyMessageBean>(this, MyMessageBean.class);
        database = messageDBHelper.getReadableDatabase();

        messageListAdapter = new MessageListAdapter(this, cursor, true);
        setListAdapter(messageListAdapter);

        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (cursor != null) {
                    cursor.moveToPosition(position);
                    String sem = cursor.getString(1);
                    String tgn = cursor.getString(8);
                    if (S.isNotEmpty(sem)) {
                        Intent intent = new Intent(MessageTaskReceived.this, MessageDetailsActivity.class);
                        intent.putExtra(MessageDetailsActivity.EXTRA_MESSAGE_TGN, tgn);
                        startActivity(intent);
                    } else {
                        showMessageFullScreen(cursor.getString(4));
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        database.close();
        database = null;
        super.onDestroy();
    }

    private void showMessageFullScreen(String txt) {
        Intent intent = new Intent(this, MessageSendDetalisActivity.class);
        intent.putExtra(MessageSendDetalisActivity.EXTRA_MESSAGE_TEXT, txt);
        startActivity(intent);
    }

    private void loadData() {

        String userName = JavaBeanManager.getInstance().getUserinfo().getEnb();

        StringBuilder sqlBuilder = new StringBuilder("SELECT ").append(COLS).append(" FROM ")
                .append(messageDBHelper.getTableName()).append(" ");
        sqlBuilder.append(" WHERE user_name = '").append(userName).append("' ");
        sqlBuilder.append(" and sem is not null and sem !='' ");
        sqlBuilder.append(" and fke = '").append(fke).append("' ");
        sqlBuilder.append(ORDER);

        cursor = database.rawQuery(sqlBuilder.toString(), null);

        Log.d("C_DB", sqlBuilder.toString());
        messageListAdapter.changeCursor(cursor);

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, new IntentFilter(ReceiveMessageThread.ACTION_MESSAGE_ARRIVED));
        loadData();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(receiver);
        super.onPause();
    }

    @Override
    public void setTitle(CharSequence title) {
        this.title.setText(title);
        super.setTitle(title);
    }

    @Override
    public void setTitle(int titleId) {
        this.setTitle(getString(titleId));
    }

    @SuppressLint("InflateParams")
    private void initactionBar() {
        final Activity context = this;

        ActionBar actionBar = getActionBar();

        actionBar.setCustomView(LayoutInflater.from(this).inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);

        this.title = (TextView) findViewById(R.id.txt_title);

        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });

        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

}
